package com.soujiayi.share;


import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.soujiayi.activity.R;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;

public class WeixinAPI {

	private IWXAPI api;
	private Context context;

	public WeixinAPI(Context context) {
		this.context = context;
		api = WXAPIFactory.createWXAPI(context, Constants.WEIXIN_APP_ID, false);
		appRegister();
	}

	public void appRegister() {
		api.registerApp(Constants.WEIXIN_APP_ID);
	}

	public void shareToWeixin() {
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = context.getResources().getString(R.string.soujiayi_phone_homepage_url);
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = context.getResources().getString(R.string.share_to_weixin_title);
		msg.description = context.getResources().getString(R.string.share_to_weixin_description);
		try{
			Bitmap thumb = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.ic_launcher);
			msg.thumbData = CommonUtils.bmpToByteArray(thumb, true);
		}catch(Exception e){
			
		}
		
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = SendMessageToWX.Req.WXSceneSession;
		api.sendReq(req);
	}
	
	public void shareToWeixin(String title, String content, String imageUrl, String url, int type) {
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = url;
		WXMediaMessage msg = new WXMediaMessage(webpage);
		if(title.length() > 10){
			title = title.substring(0, 10) + "...";
		}
		msg.title = title;
		msg.description = content;
		try{
			String picPath = Environment.getExternalStorageDirectory() +  File.separator + Constants.CACHE_DIR +  File.separator + String.valueOf(imageUrl.hashCode());
			Bitmap thumb = CommonUtils.decodeFile(new File(picPath));
			msg.thumbData = CommonUtils.bmpToByteArray(thumb, true);
		}catch(Exception e){
			
		}

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		if(type == 1){// 微信好友
			req.scene = SendMessageToWX.Req.WXSceneSession;
		}else if(type == 2){// 微信朋友圈
			req.scene = SendMessageToWX.Req.WXSceneTimeline;
		}
		api.sendReq(req);
	}
	

	private String buildTransaction(String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

}
